/*
 * @Author: zhang peng
 * @Date: 2021-08-03 10:57:51
 * @LastEditTime: 2022-05-04 21:24:16
 * @LastEditors: zhang peng
 * @Description:
 * @FilePath: /miniprogram-to-uniapp2/src/project/template/polyfill/mixins.js
 *
 * 如果你想删除本文件，请先确认它使用的范围，感谢合作~
 * 如有疑问，请直接联系: 375890534@qq.com
 */
import {
	isWeiXin
} from '@/common/common.js'
import { mallRequest } from '../we7/resource/js/service';
export default {
	data() {
		return {
			wxopenid: "",
			maskflag: false,
			uid: "",
			uniacid: "",
			domain1: "",
			urluid: "",
			checkUid: "",
		}
	},
	methods: {
		/**
		 * 转义符换成普通字符
		 * @param {*} str
		 * @returns
		 */
		escape2Html(str) {
			if (!str) return str
			var arrEntities = {
				'lt': '<',
				'gt': '>',
				'nbsp': ' ',
				'amp': '&',
				'quot': '"'
			}
			return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function(all, t) {
				return arrEntities[t]
			})
		},
		/**
		 * 普通字符转换成转义符
		 * @param {*} sHtml
		 * @returns
		 */
		html2Escape(sHtml) {
			if (!sHtml) return sHtml
			return sHtml.replace(/[<>&"]/g, function(c) {
				return {
					'<': '&lt;',
					'>': '&gt;',
					'&': '&amp;',
					'"': '&quot;'
				} [c]
			})
		},
		/**
		 * setData polyfill 勿删!!!
		 * 用于转换后的uniapp的项目能直接使用this.setData()函数
		 * @param {*} obj
		 * @param {*} callback
		 */
		setData: function(obj, callback) {
			let that = this
			const handleData = (tepData, tepKey, afterKey) => {
				var tepData2 = tepData
				tepKey = tepKey.split('.')
				tepKey.forEach(item => {
					if (tepData[item] === null || tepData[item] === undefined) {
						let reg = /^[0-9]+$/
						tepData[item] = reg.test(afterKey) ? [] : {}
						tepData2 = tepData[item]
					} else {
						tepData2 = tepData[item]
					}
				})
				return tepData2
			}
			const isFn = function(value) {
				return typeof value == 'function' || false
			}
			Object.keys(obj).forEach(function(key) {
				let val = obj[key]
				key = key.replace(/\]/g, '').replace(/\[/g, '.')
				let front, after
				let index_after = key.lastIndexOf('.')
				if (index_after != -1) {
					after = key.slice(index_after + 1)
					front = handleData(that, key.slice(0, index_after), after)
				} else {
					after = key
					front = that
				}
				if (front.$data && front.$data[after] === undefined) {
					Object.defineProperty(front, after, {
						get() {
							return front.$data[after]
						},
						set(newValue) {
							front.$data[after] = newValue
							that.hasOwnProperty("$forceUpdate") && that.$forceUpdate()
						},
						enumerable: true,
						configurable: true
					})
					front[after] = val
				} else {
					that.$set(front, after, val)
				}
			})
			// this.$forceUpdate();
			isFn(callback) && this.$nextTick(callback)
		},
		/**
		 * 解析事件里的动态函数名，这种没有()的函数名，在uniapp不被执行
		 * 比如：<view bindtap="{{openId==undefined?'denglu':'hy_to'}}">立即</view>
		 * @param {*} exp
		 */
		parseEventDynamicCode(e, exp) {
			if (typeof(this[exp]) === 'function') {
				this[exp](e)
			}
		},
		/**
		 * 用于处理对props进行赋值的情况
		 * //简单处理一下就行了
		 *
		 * @param {*} target
		 * @returns
		 */
		deepClone(target) {
			return JSON.parse(JSON.stringify(target))
		},
		/**
		 * 用于处理dataset
		 * 自定义组件的事件里，是获取不到e.currentTarget.dataset的
		 * 因此收集data-参数，手动传进去
		 *
		 * @param {*} event
		 * @param {*} dataSet
		 * @returns
		 */
		datasetHandle(event, dataSet = {}) {
			if (event && !event.currentTarget) {
				if (dataSet.tagId) {
					event.currentTarget = {
						id: dataSet.tagId
					}
				} else {
					event.currentTarget = {
						dataset: dataSet
					}
				}
			}
		},
		getUniacid(liveId) {
			return new Promise((resolve, reject) => {
				getApp().globalData.util.request({
					url: `wechat&r=getUniacid&token=${liveId}`,
					data: {
						token: liveId
					},
					cachetime: '0',
					showLoading: true,
					success: (res) => {
						this.uniacid = res.data.data.uniacid;
						this.domain1 = document.domain; //res.data.data.domain;
						this.urluid = this.getUrlCode().uid;
						this.checkUid = uni.getStorageSync('uid_' + this.uniacid);
						resolve('success');
						//if(urluid!= null && urluid!= '' && urluid!= undefined)
						//	uni.setStorageSync('uid__'+uniacid, urluid);
						//console.log(this.urluid)
					},
					fail: (err) => {
						console.log(err);
						reject('error');
					}
				});
			});
		}
		//得到code
		,
		async getCode() {
			//console.log(isWeiXin(),'weixin');
			// await this.getUniacid(liveId);
			// //console.log(this.uniacid);
			// if (this.getUrlCode().token && this.getUrlCode().bank_app != 1) //'c7191a83f2b70afd'
			// {
			// 	console.log(this.checkUid)
			// 	if (this.checkUid == null || this.checkUid == '' || this.checkUid == undefined) {
			// 		console.log('------------------------')
			// 		if (this.urluid != null && this.urluid != '' && this.urluid != undefined) {
			// 			console.log('22')
			// 			uni.setStorageSync('uid_' + this.uniacid, this.urluid);
			// 		} else {
			// 			var wxUrl =
			// 				`http://${this.domain1}/app/wxapp.php?m=wxz_wzbagent&do=wechat&c=entry&a=wxapp&token=${this.getUrlCode().token}&r=h5login`;
			// 			window.location.href = wxUrl;
			// 		}
			// 	}
			// }
			this.uid = this.getUrlCode().uid; // 截取code
			this.wxopenid = this.getUrlCode().wxopenid;
			// */this.uniacid = this.getUrlCode().uniacid;
			// if (this.uniacid || this.uniacid == 'undefined')
			// 	uni.setStorageSync('uniacid', res.data.data.uniacid);
			// let suniacid = uni.getStorageSync('uniacid');
			// let sdomain = uni.getStorageSync('domain');*/
			//this.last_uniacid = this.getUrlCode().last_uniacid;
			let suid = uni.getStorageSync('uid');
			let swxopenid = uni.getStorageSync('wxopenid');
			let token = this.getUrlCode().token;
			let xuan_id = this.getUrlCode().xuan_id;
			let skip = this.getUrlCode().skip;
			if (suid == null || suid == '' || suid == undefined) {
				this.maskflag = true;
			}
			if ((this.uid == null || this.uid == '' || this.uid == undefined) &&
				(suid == null || suid == '' || suid == undefined) && 
				skip != 1 &&
				this.getUrlCode().bank_app != 1) {
				if (/AlipayClient/i.test(window.navigator.userAgent)) {
					var wxUrl =
						`http://${document.domain}/app/wxapp.php?m=wxz_wzbagent&do=ali&c=entry&a=wxapp&token=c7191a83f2b70afd&r=h5login&app_type=alih5`;
					window.location.href = wxUrl;
				} else {
					var wxUrl =
						`http://${document.domain}/app/wxapp.php?m=wxz_wzbagent&do=wechat&c=entry&a=wxapp&token=${token}&xuan_id=${token}&r=h5login`;
					window.location.href = wxUrl;
				}
			} else if (this.uid) {
				// 例子url http://25807368.3udctvas.h5live.rwkaa.top/h5/?token=c7191a83f2b70afd&s=1701673600&wxopenid=og_kH6UsocyIpAPlcKb_6M1BqD_o&uid=17167368&uniacid=389
				// 需要保存url的参数wxopenid uid uniacid 并清理url的参数 没有s就404(可以放在最后弄)
				// 然后movie/movie里的 lives_new&r=payGift 需要传wxopenid uid uniacid
				uni.setStorageSync('uid', this.uid);
				uni.setStorageSync('wxopenid', this.wxopenid);
				uni.setStorageSync('uniacid', this.getUrlCode().uniacid);


				
				// this.setData({
				// 	is_black: 0
				// });
				// let token = this.getUrlCode().token;
				// var url = window.location.href; //获取当前页面的url
				// if (url.indexOf("?") != -1) { //判断是否存在参数
				// 	url = url.replace(/(\?|#)[^'"]*/, ''); //去除参数
				// 	var new_url = url + '?token=' + token
				// 	window.history.pushState({}, 0, new_url);
				// }
			} else if ((this.uid == null || this.uid == '' || this.uid == undefined) && suid) {
				//执行下一步代码
			}
			if (skip == 1){
				uni.clearStorageSync();
			}
			// const urlParams = new URLSearchParams(window.location.search);
			// urlParams.delete('uniacid'); //删除url上面的uniacid参数
			// urlParams.delete('uid'); //删除url上面的uid参数
			// urlParams.delete('wxopenid'); //删除url上面的wxopenid参数
			// var paramValue = urlParams.get('s');
			// urlParams.delete('s'); //删除url上面的wxopenid参数
			// window.location.search = urlParams.toString();
			// urlParams.get("s");
			var url = new URL(window.location.href);
			var params = new URLSearchParams(url.search);
			let paramValue = params.get('s');
			params.delete("s");
			params.delete("wxopenid");
			params.delete("uid");
			params.delete('uniacid');
			params.delete('skip');
			var newUrl = url.origin + url.pathname + '?' + params.toString();
			history.replaceState(null, "", newUrl);
		
			uni.setStorageSync('page_type', '正常');
			// if(paramValue){
			// 		uni.setStorageSync('page_type', '正常');
			// 		console.log(111)
			// 		return
			// }else{
			// 	uni.setStorageSync('page_type', 404);
			// 	console.log(222)
			// }
			/*
						//入口状态 首次访问 第一次访问入口
						if((!this.uniacid || this.uniacid == 'undefined') && (!suniacid || suniacid == 'undefined')){
							getApp().globalData.util.request({
								url: `wechat&r=getUniacid&token=${token}`,
								data: {
									token: token
								},
								cachetime: '0',
								showLoading: true,
								success: (res) => {
									if(res.data.data.uniacid && res.data.data.domain)
									{
										//保存公众号id和跳转的域名到入口域名下
										uni.setStorageSync('uniacid', res.data.data.uniacid);
										uni.setStorageSync('domain', res.data.data.domain);
									}
									window.location.href = `http://${res.data.data.domain}/app/wxapp.php?m=wxz_wzbagent&do=wechat&c=entry&a=wxapp&token=${token}&xuan_id=${xuan_id}&r=h5login`;
								},
								fail: (err) => {
								}
							});
						} else if(suniacid && suniacid != 'undefined' && sdomain && sdomain != 'undefined' && document.domain != sdomain){	
						//入口状态 原先有过记录 第2-n次访问入口
							window.location.href = `http://${sdomain}/h5/?token=${token}&xuan_id=${xuan_id}&uniacid=${suniacid}`;
						} else if(this.uid && this.uid != 'undefined' && this.wxopenid && this.wxopenid != 'undefined'){
						//落地状态 登录后url有数据本地无数据
							uni.setStorageSync('uid', this.uid);
							uni.setStorageSync('wxopenid', this.wxopenid);
							return true;
						} else if(suid && suid != 'undefined' && swxopenid && swxopenid != 'undefined'){
						//落地状态 有本地数据
							return true;
						}
						//结束
						return false;
			*/


		},
		async getCode_newvoteinfo(liveId) {
			console.log("mixins")
			await this.getUniacid(liveId);
			// var urlParams = new URLSearchParams(window.location.search);
			// this.uid = urlParams.get("uid")
			// this.wxopenid= urlParams.get("wxopenid")
			// // this.uid = this.getUrlCode().uid; // 截取code
			// // this.wxopenid = this.getUrlCode().wxopenid;
			// uni.setStorageSync('uid', this.uid);
			// uni.setStorageSync('wxopenid', this.wxopenid);
			// console.log(this.uid,this.wxopenid,249,urlParams)
			// var url = new URL(window.location.href);
			// var params = new URLSearchParams(url.search);
			// params.delete("wxopenid");
			// params.delete("uid");
			// var newUrl = url.origin + url.pathname + '?' + params.toString();
			// history.replaceState(null, "", newUrl);
		},
		async getCode_voteinfo(liveId) {
			if (this.getUrlCode().bank_app != 1) {

			} else {
				await this.getUniacid(liveId);
				console.log(this.uniacid, 6666666666);
				if (this.getUrlCode().token) //'c7191a83f2b70afd'
				{
					console.log(this.checkUid)
					if (this.checkUid == null || this.checkUid == '' || this.checkUid == undefined) {
						console.log('------------------------')
						if (this.urluid != null && this.urluid != '' && this.urluid != undefined) {

							console.log('22')
							uni.setStorageSync('uid_' + this.uniacid, this.urluid);
						} else {
							var wxUrl =
								`http://${this.domain1}/app/wxapp.php?m=wxz_wzbagent&do=wechat&c=entry&a=wxapp&token=${this.getUrlCode().token}&xuan_id=${this.getUrlCode().xuan_id}&r=h5login`;
							window.location.href = wxUrl;
						}
					}

				}
				this.uid = this.getUrlCode().uid; // 截取code
				this.wxopenid = this.getUrlCode().wxopenid;
				let suid = uni.getStorageSync('uid');
				let swxopenid = uni.getStorageSync('wxopenid');
				let token = this.getUrlCode().token;
				if (suid == null || suid == '' || suid == undefined) {
					this.maskflag = true;
				}
				if ((this.uid == null || this.uid == '' || this.uid == undefined) && (suid == null || suid == '' ||
						suid == undefined)) {
					var wxUrl =
						`http://${this.domain1}/app/wxapp.php?m=wxz_wzbagent&do=wechat&c=entry&a=wxapp&token=${token}&xuan_id=${this.getUrlCode().xuan_id}&r=h5login`;
					window.location.href = wxUrl;
				} else if (this.uid) {
					console.log(11111111111111111111111111)
					uni.setStorageSync('uid', this.uid);
					uni.setStorageSync('wxopenid', this.wxopenid);
					this.setData({
						is_black: 0
					});
					if (window.location.port != "") {
						var port = "";
						//var port=':'+window.location.port;
					} else {
						var port = "";
					}
					let token = this.getUrlCode().token;
					let xuanid = this.getUrlCode().xuan_id;
					window.location.href = window.location.protocol + '//' + window.location.host + port + window
						.location.pathname + '?xuan_id=' + xuanid + '&token=' + token;
				} else if ((this.uid == null || this.uid == '' || this.uid == undefined) && suid) {
					//执行下一步代码
				}
			}
		},
		getUrlCode() { // 截取url中的code方法
			var url = location.search
			this.winUrl = url
			var theRequest = new Object()
			if (url.indexOf("?") != -1) {
				var str = url.substr(1)
				var strs = str.split("&")
				for (var i = 0; i < strs.length; i++) {
					theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
				}
			}
			//console.log(theRequest)
			return theRequest
		},
		refreshmovie() {
			location.reload();
		},
		share(liveId, xuan_id) {
			console.log('测')
			var xuanPara = xuan_id ? `&xuan_id=${xuan_id}` : '';
			var uniacid = uni.getStorageSync('uniacid')
			//var specialPara = special_id?`&special_id=${special_id}`:'';
			getApp().globalData.util.request({
				url: `wechat&r=shareData&token=${liveId}${xuanPara}&uniacid=${uniacid}`,
				success: (t) => {
					if(t.data.data.unionid)
					{
						mallRequest({
						    url: '?s=/api/passport/loginByWxUnionid',
						    data: {
						        unionid: t.data.data.unionid
						    }
						}).then((res) => {
						    if (res.data.token) {
						        uni.setStorageSync('mall_token', res.data.token);
						    }
						});
					}
					//var appid = getApp().globalData.siteInfo.appid;
					var jssdk_config = t.data.data.jssdk_config;
					var share_data = t.data.data.share_data;
					var debug = this.getUrlCode().token == 'e4a4534fce9111bf'?false:false;
					let uid = uni.getStorageSync('uid');
					//console.log(jssdk_config);
					//console.log(share_data);
					jWeiXin.config({
						debug: debug,
						appId: jssdk_config.appId, // 必填，公众号的唯一标识
						timestamp: jssdk_config.timestamp, // 必填，生成签名的时间戳
						nonceStr: jssdk_config.nonceStr, // 必填，生成签名的随机串
						signature: jssdk_config.signature, // 必填，签名，见附录1
						jsApiList: ['checkJsApi', 'updateAppMessageShareData',
							'updateTimelineShareData', 'onMenuShareAppMessage',
							'onMenuShareTimeline'
						] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
					});
					jWeiXin.ready(function() {
						jWeiXin.checkJsApi({
							jsApiList: ['checkJsApi', 'updateAppMessageShareData',
								'updateTimelineShareData', 'onMenuShareAppMessage',
								'onMenuShareTimeline'
							], // 需要检测的JS接口列表，所有JS接口列表见附录2,
							success: function(res) {
								console.log('checkjsapi Success');
								console.log(res);
							},
							fail: function(res) {
								console.log('res');
								console.log(res);
							}
						});
						jWeiXin.updateAppMessageShareData({
							title: share_data.title, // 分享标题
							desc: share_data.desc, // 分享描述
							link: share_data.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
							imgUrl: share_data.imgUrl, // 分享图标
							success: function() {
								console.log('分享朋友成功！')
							},
							fail: function() {
								console.log(12312);
							}
						});
						jWeiXin.updateTimelineShareData({
							title: share_data.title, // 分享标题
							link: share_data.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
							imgUrl: share_data.imgUrl, // 分享图标
							success: function() {
								console.log('分享朋友圈成功！')
							},
							fail: function() {
								console.log(12312);
							}
						});

						jWeiXin.onMenuShareTimeline({
							title: share_data.title, // 分享标题
							link: share_data.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
							imgUrl: share_data.imgUrl, // 分享图标
							success: function() {
								console.log('分享朋友圈成功2！')
							},
							fail: function() {
								console.log(12312);
							}
						});

						jWeiXin.onMenuShareAppMessage({
							title: share_data.title, // 分享标题
							desc: share_data.desc, // 分享描述
							link: share_data.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
							imgUrl: share_data.imgUrl, // 分享图标
							type: '', // 分享类型,music、video或link，不填默认为link
							dataUrl: '', // 如果 type 是music或video，则要提供数据链接，默认为空
							success: function() {
								console.log('分享朋友成功2！')
							}
						});
					});
					jWeiXin.error(function(res) {
						console.log(res);
					});
				}
			})
		},
		getSpecialShareData(special_id) {
			getApp().globalData.util.request({
				url: `wechat&r=specialShareData&special_id=${special_id}`,
				success: (t) => {
					//var appid = getApp().globalData.siteInfo.appid;
					var jssdk_config = t.data.data.jssdk_config;
					var share_data = t.data.data.share_data;
					var debug = this.getUrlCode().debug;

					//console.log(jssdk_config);
					//console.log(share_data);
					jWeiXin.config({
						debug: debug,
						appId: jssdk_config.appId, // 必填，公众号的唯一标识
						timestamp: jssdk_config.timestamp, // 必填，生成签名的时间戳
						nonceStr: jssdk_config.nonceStr, // 必填，生成签名的随机串
						signature: jssdk_config.signature, // 必填，签名，见附录1
						jsApiList: [
							"checkJsApi",
							"updateAppMessageShareData",
							"updateTimelineShareData",
							"onMenuShareAppMessage",
							"onMenuShareTimeline"
						] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
					});
					jWeiXin.ready(function() {
						jWeiXin.checkJsApi({
							jsApiList: [
								"checkJsApi",
								"updateAppMessageShareData",
								"updateTimelineShareData",
								"onMenuShareAppMessage",
								"onMenuShareTimeline"
							], // 需要检测的JS接口列表，所有JS接口列表见附录2,
							success: function(res) {
								console.log("checkjsapi Success");
								console.log(res);
							},
							fail: function(res) {
								console.log("res");
								console.log(res);
							}
						});
						jWeiXin.updateAppMessageShareData({
							title: share_data.title,
							desc: share_data.desc,
							link: share_data.link,
							imgUrl: share_data.imgUrl,
							success: function() {
								console.log("分享朋友成功！");
							}
						});
						jWeiXin.updateTimelineShareData({
							title: share_data.title,
							link: share_data.link,
							imgUrl: share_data.imgUrl,
							success: function() {
								console.log("分享朋友圈成功！");
							}
						});

						jWeiXin.onMenuShareTimeline({
							title: share_data.title,
							link: share_data.link,
							imgUrl: share_data.imgUrl,
							success: function() {
								console.log("分享朋友圈成功2！");
							}
						});

						jWeiXin.onMenuShareAppMessage({
							title: share_data.title,
							desc: share_data.desc,
							link: share_data.link,
							imgUrl: share_data.imgUrl,
							type: "",
							dataUrl: "",
							success: function() {
								console.log("分享朋友成功2！");
							}
						});
					});
					jWeiXin.error(function(res) {
						console.log(res);
					});
				}
			});
		}


	}
}